require 'rails_generator/generators/components/scaffold/scaffold_generator'

class BcmsScaffoldResourceSandbox
  include ActionView::Helpers::ActiveRecordHelper

  attr_accessor :form_action, :singular_name, :suffix, :model_instance

  def sandbox_binding
    binding
  end

  def default_input_block
    Proc.new { |record, column| <<-END_ROW 
<tr valign="top">
	<td class="leftCol">#{column.human_name}:</td>
	<td class="rightCol">#{input(record, column.name, :limit => column.limit)}
  <%= error_message_on '#{record}', '#{column.name}' %></td>
</tr>
END_ROW
    }
  end
end

class ActionView::Helpers::InstanceTag
  def to_input_field_tag(field_type, options={})
    field_meth = "#{field_type}_field"
    limit = options.delete(:limit)
    the_limit = ""
    the_limit = "'size' => #{limit}, " if limit and limit < 255
    "<%= #{field_meth} \"#{@object_name}\", \"#{@method_name}\", #{the_limit}'class'=>\"input-text\"#{options.empty? ? '' : ', '+options.inspect} %>"
  end

  def to_text_area_tag(options = {})
    limit = options.delete(:limit)
    "<%= text_area \"#{@object_name}\", \"#{@method_name}\", 'class'=>\"input-text-area\"#{options.empty? ? '' : ', '+ options.inspect} %>"
  end

  def to_date_select_tag(options = {})
    limit = options.delete(:limit)
    "<%= date_select '#{@object_name}', '#{@method_name}' #{options.empty? ? '' : ', '+ options.inspect} %>"
  end

  def to_datetime_select_tag(options = {})
    limit = options.delete(:limit)
    "<%= datetime_select '#{@object_name}', '#{@method_name}' #{options.empty? ? '' : ', '+ options.inspect} %>"
  end
  
  def to_time_select_tag(options = {})
    limit = options.delete(:limit)
    "<%= time_select '#{@object_name}', '#{@method_name}' #{options.empty? ? '' : ', '+ options.inspect} %>"
  end

  def to_boolean_select_tag(options = {})
    limit = options.delete(:limit)
    "<%= check_box \"#{@object_name}\", \"#{@method_name}\", 'class'=>\"input-checkbox\"#{options.empty? ? '' : ', '+ options.inspect} %>"
  end
end

# class BhedanaScaffoldResourceGenerator < ScaffoldGenerator
class BcmsScaffoldResourceGenerator < Rails::Generator::NamedBase
  default_options :skip_migration => false
  
  attr_reader   :controller_name,
                :controller_class_path,
                :controller_file_path,
                :controller_class_nesting,
                :controller_class_nesting_depth,
                :controller_class_name,
                :controller_singular_name,
                :controller_plural_name,
                :resource_edit_path,
                :default_file_extension
  alias_method  :controller_file_name,  :controller_singular_name
  alias_method  :controller_table_name, :controller_plural_name

  def initialize(runtime_args, runtime_options = {})
    super

    @controller_name = @name.pluralize

    base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
    @controller_class_name_without_nesting, @controller_singular_name, @controller_plural_name = inflect_names(base_name)

    if @controller_class_nesting.empty?
      @controller_class_name = @controller_class_name_without_nesting
    else
      @controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
    end
    
    if ActionView::Base.const_defined?('DEFAULT_TEMPLATE_HANDLER_PREFERENCE') &&
       ActionView::Base::DEFAULT_TEMPLATE_HANDLER_PREFERENCE.include?(:erb) then
      @resource_generator = "scaffold"
      @default_file_extension = "html.erb"
      @resource_edit_path = "/edit"
    else
      @resource_generator = "scaffold_resource"
      @default_file_extension = "rhtml"
      @resource_edit_path = ";edit"
    end
    
  end

  def manifest
    record do |m|
      # Check for class naming collisions.
      m.class_collisions(controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper")
      m.class_collisions(class_path, "#{class_name}")

      # Controller, helper, views
      m.directory(File.join('app/models', class_path))
      m.directory(File.join('app/controllers', controller_class_path))
      m.directory(File.join('app/helpers', controller_class_path))
      m.directory(File.join('app/views', controller_class_path, controller_file_name))

      # test directories.
      m.directory(File.join('test/functional', controller_class_path))
      m.directory(File.join('test/unit', class_path))

      # spec directories.
      m.directory(File.join('spec/controllers', class_path))
      m.directory(File.join('spec/fixtures', class_path))
      m.directory(File.join('spec/helpers', class_path))
      m.directory(File.join('spec/models', class_path))
      m.directory(File.join('spec/views', controller_class_path, controller_file_name))

      for action in scaffold_views
        m.template(
          "view_#{action}.rhtml",
          File.join('app/views', controller_class_path, controller_file_name, "#{action}.rhtml")
        )
      end

      m.complex_template "form.rhtml",
        File.join('app/views', controller_class_path, controller_file_name, "_form.rhtml"),
        :insert => 'form_scaffolding.rhtml',
        :sandbox => lambda { create_sandbox },
        :begin_mark => 'form',
        :end_mark => 'eoform',
        :mark_id => singular_name
        
      # Layout and stylesheet.
      m.template('layout.rhtml', File.join('app/views/layouts', controller_class_path, "#{controller_file_name}.rhtml"))
      m.template('style.css', 'public/stylesheets/scaffold.css')

      m.template('model.rb', File.join('app/models', class_path, "#{file_name}.rb"))

      m.template(
        'controller.rb', File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb")
      )

      m.template('helper.rb',          File.join('app/helpers',     controller_class_path, "#{controller_file_name}_helper.rb"))

      m.template('spec_controller.rb', File.join('spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb"))
      m.template('spec_helper.rb', File.join('spec/helpers', controller_class_path, "#{controller_file_name}_helper_spec.rb"))
      m.template('spec_model.rb', File.join('spec/models', controller_class_path, "#{controller_file_name}_spec.rb"))
      m.template('fixtures.yml',       File.join('spec/fixtures', "#{table_name}.yml"))

      # specs for each Scaffolded views.
      scaffold_views.each do |action|
        m.template "spec_view_#{action}.rb",
                   File.join('spec/views',
                             controller_class_path,
                             controller_file_name,
                             "#{action}.rhtml_spec.rb"),
                   :assigns => { :action => action }
      end

      unless options[:skip_migration]
        m.migration_template(
          'migration.rb', 'db/migrate', 
          :assigns => {
            :migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}",
            :attributes     => attributes
          }, 
          :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
        )
      end

      m.route_resources controller_file_name
    end
  end
    
  protected
    # Override with your own usage banner.
    def banner
      "Usage: #{$0} scaffold_resource ModelName [field:type, field:type]"
    end

    def scaffold_views
      %w[ index show new edit ]
    end
    
    def add_options!(opt)
      opt.separator ''
      opt.separator 'Options:'
      opt.on("--skip-migration",
             "Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
    end
    
    def model_name 
      class_name.demodulize
    end

    def suffix
      "_#{singular_name}" if options[:suffix]
    end
    
    def create_sandbox
      sandbox = BcmsScaffoldResourceSandbox.new
      sandbox.singular_name = singular_name
      begin
        sandbox.model_instance = model_instance
        sandbox.instance_variable_set("@#{singular_name}", sandbox.model_instance)
      rescue ActiveRecord::StatementInvalid => e
          logger.error "Before updating scaffolding from new DB schema, try creating a table for your model (#{class_name})"
          raise SystemExit
      end
      sandbox.suffix = suffix
      sandbox
    end

    def model_instance
      base = class_nesting.split('::').inject(Object) do |base, nested|
        break base.const_get(nested) if base.const_defined?(nested)
        base.const_set(nested, Module.new)
      end
      unless base.const_defined?(@class_name_without_nesting)
        base.const_set(@class_name_without_nesting, Class.new(ActiveRecord::Base))
      end
      class_name.constantize.new
    end
end

module Rails
  module Generator
    class GeneratedAttribute
      def default_value
        @default_value ||= case type
          when :int, :integer               then "\"1\""
          when :float                       then "\"1.5\""
          when :decimal                     then "\"9.99\""
          when :datetime, :timestamp, :time then "Time.now"
          when :date                        then "Date.today"
          when :string                      then "\"MyString\""
          when :text                        then "\"MyText\""
          when :boolean                     then "false"
          else
            ""
        end      
      end

      def input_type
        @input_type ||= case type
          when :text                        then "textarea"
          else
            "input"
        end      
      end
    end
  end
end

